//
//  SEExamineListViewController.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/8.
//

import UIKit

enum SEExamineListViewControllerType {
    case examineList
    case seneAIReport

    var title: String {
        switch self {
        case .examineList: return "检查记录"
        case .seneAIReport: return "发送检查报告"
        }
    }
}

class SEExamineListViewController: SEBaseViewController {

    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.se_header = SERefreshHeader { [weak self] in self?.loadNewData() }
            tableView.se_footer = SERefreshFooter { [weak self] in self?.loadMoreData() }
            tableView.se_empty = SEEmptyView { [weak self] in self?.requestMyExamineList() }
            
            tableView.register(SEExamineRecordListCell.nibForCell(),
                               forCellReuseIdentifier: SEExamineRecordListCell.reuseIdentifier())

            tableView.register(SEChatExamineListCell.nibForCell(),
                               forCellReuseIdentifier: SEChatExamineListCell.reuseIdentifier())
        }
    }

    var sendHandler: ((SEExamineDetailViewModel) -> Void)?
    var type: SEExamineListViewControllerType! = .examineList
    var viewModel = SEExamineListViewModel()

    convenience init(type: SEExamineListViewControllerType = .examineList) {
        self.init()
        self.type = type
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = type.title
        requestMyExamineList()
    }

    override func setupUI() {
        super.setupUI()

        viewModel.updateData = { [weak self] status in
            self?.tableView.se_empty?.allowShow = true
            self?.endRefreshing()
            switch status {
            case .success:
                self?.tableView.reloadData()
            case .auth(let msg):
                self?.presentLoginViewController(selector: #selector(self?.requestMyExamineList)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.aiReporeCreateHandler = { [weak self] status in
            switch status {
            case .success:
                SEHUD.show(message: "提交成功")
                self?.requestMyExamineList()
            case .auth(let msg):
                self?.presentLoginViewController(selector: #selector(self?.createAIReport)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                self?.showAlert(type: .createFailed(msg ?? ""))
            }
        }
    }

    private func pushExamineRecord() {
        let detailVc = SEExamineRecordViewController(with: viewModel.selectedViewModel)
        detailVc.title = "检查记录"
        navigationController?.pushViewController(detailVc, animated: true)
    }

    private func pushAIReportDetail() {
        let urlStr = SEApiManager.examineAIReportUrl(applyFormId: viewModel.selectedViewModel.model.id,
                                                     hospitalId: viewModel.selectedViewModel.model.checkHosId,
                                                     status: viewModel.selectedViewModel.model.aiStatus)
        let webVc = SEWebViewController(url: URL(string: urlStr),
                                        title: viewModel.selectedViewModel.reportTitle)
        navigationController?.pushViewController(webVc, animated: true)
    }

    private func popChat() {
        sendHandler?(viewModel.selectedViewModel)
        navigationController?.popViewController(animated: true)
    }

    private func showAlert(type: SEExamineAlertViewType) {
        let alert = UINib.loadViewFrom(SEExamineAlertView.self)
        alert.frame = CGRect(x: 0, y: 0, width: UIScreen.screenWidth, height: UIScreen.screenHeight)
        alert.confirmBtnHandler = { [weak self] type in
            guard type == .waticreate || type == .createFailed("") else { return }
            self?.createAIReport()
        }
        alert.show(type)
    }
}

// MARK: - UITableViewDataSource

extension SEExamineListViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.numberOfSections
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if type == .examineList {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEExamineRecordListCell.reuseIdentifier(), for: indexPath) as! SEExamineRecordListCell
            cell.delegate = self
            cell.updateWithViewModel(viewModel.rowViewModel(indexPath: indexPath), indexPath)
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEChatExamineListCell.reuseIdentifier(), for: indexPath) as! SEChatExamineListCell
            cell.delegate = self
            cell.update(with: viewModel.rowViewModel(indexPath: indexPath), indexPath)
            return cell
        }
    }
}

// MARK: - UITableViewDelegate

extension SEExamineListViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let selectedVm = viewModel.rowViewModel(indexPath: indexPath)
        viewModel.selectedViewModel = selectedVm
        pushExamineRecord()
    }
}

// MARK: - SEExamineRecordListCellDelegate

extension SEExamineListViewController: SEExamineRecordListCellDelegate {
    func examineRecordListCellAIButtonAction(indexPath: IndexPath, actionType: SEExamineRecordListCellActionType) {
        viewModel.selectedViewModel = viewModel.rowViewModel(indexPath: indexPath)
        switch actionType {
        case .ai:
            var type = SEExamineAlertViewType.unknown
            if viewModel.selectedViewModel.aiStauts == .waticreate {
                type = .waticreate
            }
            if viewModel.selectedViewModel.aiStauts == .creating{
                type = .creating
            }
            showAlert(type: type)
        case .report:
            pushAIReportDetail()
        }

    }
}

// MARK: - SEChatExamineListCellDelegate

extension SEExamineListViewController: SEChatExamineListCellDelegate {
    func sendReportDidTapped(_ cell: SEChatExamineListCell, _ indexPath: IndexPath) {
        viewModel.selectedViewModel = viewModel.rowViewModel(indexPath: indexPath)
        guard viewModel.selectedViewModel.checkStatus == .finish else {
            showAlert(type: .unsupport)
            return
        }
        popChat()
    }
}

// MARK: - APIRequest
extension SEExamineListViewController {
    @objc private func requestMyExamineList() {
        tableView.se_header?.beginRefreshing()
    }

    private func endRefreshing() {
        tableView.endHeaderRefreshing()
        tableView.endFooterRefreshing(hasMore: viewModel.hasMore)
    }

    private func loadNewData() {
        viewModel.page = 1
        viewModel.requestMyExamineList(selectSource: 1)
    }

    private func loadMoreData() {
        viewModel.page += 1
        viewModel.requestMyExamineList(selectSource: 1)
    }

    @objc private func createAIReport() {
        viewModel.createExamineAIReport()
    }

}


